using System;
using System.IO;
using System.Web;
using System.Text;

/// <summary>
/// Http Module to save log for Weborb requests
/// </summary>
public class WeborbQueryStringModule : IHttpModule
{
    #region IHttpModule Members

    public void Dispose()
    {
        // Nothing to dispose
    }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(context_BeginRequest);
    }

    #endregion

    void context_BeginRequest(object sender, EventArgs e)
    {
        HttpContext Context = HttpContext.Current;
        var path = Context.Request.Path;

        //check if this is weborb request
        if (path.Contains("weborb"))
        {
            //read the content of this request
            Context.Request.InputStream.Position = 0;
            var bytes = new byte[Context.Request.InputStream.Length];
            Context.Request.InputStream.Read(bytes, 0, bytes.Length);
            Context.Request.InputStream.Position = 0;
            string content = Encoding.UTF8.GetString(bytes);

            if (content.Contains("Keepo"))
            {
                //get the details of this request
                var startIndex = content.IndexOf("Keepo");
                var endIndex = content.IndexOf("\0", startIndex);
                //var endIndex2 = content.IndexOf("\t", startIndex);
                //var closestEnd = Math.Min(endIndex, endIndex2);
                var methodName = content.Substring(startIndex, endIndex - startIndex);

                var time = DateTime.Now.AddHours(-2);
                var miliseconds = time.Millisecond.ToString();
                if (miliseconds.Length == 2)
                {
                    miliseconds = "0" + miliseconds;
                }
                if (miliseconds.Length == 1)
                {
                    miliseconds = "00" + miliseconds;
                }

                var curTime = time.ToString("yyyy-MM-dd HH:mm:ss") + "." + miliseconds;

                var ip = Context.Request.ServerVariables["REMOTE_ADDR"];

                var directory = Context.Server.MapPath("~/weborbLogs/");
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                var file = directory + "webOrbLog.txt";

                try
                {
                    using (StreamWriter sw = new StreamWriter(file, true))
                    {
                        //write the log record to the file
                        sw.WriteLine(ip + " " + curTime + " " + methodName);
                        sw.Flush();
                    }
                }
                catch
                {

                }
            }
        }
    }
}
